/**
 *  弹窗
 * @author xiaoxujs
 */

import { FC, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { FormBox, FormItemBox, ModalBox } from "./style";
import { ButtonX, InputX, RadioX, SelectX } from "../../../../../../components/UiManagement";
import { ISyhtDictEventItemAddEventItemParams, ISyhtDictEventItemGetDictEventItemById, ISyhtDictEventItemGetDictEventPageRes, ISyhtDictEventItemUpdateEventItemParams } from "../../../../../../type/ConfigManagement/DicManaged/DicManagedEventList";
import { dicColor, dicInterval, dicWarnType, getLabelByValue, isStoreList } from "../../../../../../assets/data/dicData";
import { ISyhtDictRuleGetDictRuleAll } from "../../../../../../type/ConfigManagement/DicManaged/DicManagedRule";
import { postSyhtDictRuleGetDictRuleAll } from "../../../../../../api/ConfigManagement/DicManaged/DicManagedRuleApi";
import { INoFenye } from "../../../../../../type/common";
import { ISelectProps } from "../../../../../../type/components";
import { handleGetDictionaryItemValueLabel } from "../../../../../../assets/fun/DictionaryItem";
import { getSyhtDictEventItemGetDictEventItemById, postSyhtDictEventItemAddEventItem, postSyhtDictEventItemUpdateEventItem } from "../../../../../../api/ConfigManagement/DicManaged/DicManagedEventListApi";
import { message } from "antd";

const AddChangeModule: FC<{
    open: boolean,
    onClose: () => void, // 关闭弹窗
    changeData?: ISyhtDictEventItemGetDictEventPageRes   // 修改的数据
    eventId?: string, // 事件组ID
    clickId?: string, // 点击的ID:
}> = ({
    open,
    onClose,
    changeData,
    eventId,
    clickId
}) => {
        const ModuleBoxRef = useRef<HTMLDivElement>(null); // 弹窗的ref 外层
        const moduleBoxContentRef = useRef<HTMLDivElement>(null); // 弹窗的ref 内层
        const [messageApi, contextHolder] = message.useMessage();

        const [addrNum, setAddrNum] = useState<string>(''); // 地址序号
        const [infoName, setInfoName] = useState<string>(''); // 信息点名称
        // const [parserRule, setParserRule] = useState<string>(); // 解析规则
        const [parserRuleId, setParserRuleId] = useState<string>(); // 解析规则ID
        const [warnType, setWarnType] = useState<string>(); // 告警类型
        const [eventColor, setEventColor] = useState<string>(); //事件颜色
        const [isStore, setIsStore] = useState<string>('0'); //是否存储
        const [storeInterval, setStoreInterval] = useState<string>(); //     存储间隔
        const [storeDay, setStoreDay] = useState<string>(''); //     存储天数

        const [parserRuleList, setParserRuleList] = useState<ISelectProps[]>([]); //解析规则列表

        const parserRule = useMemo(() => {
            return parserRuleId ? getLabelByValue(parserRuleId, parserRuleList) : ''
        }, [parserRuleId, parserRuleList])

        const parserRuleFun = useCallback(
            async (params: { ruleName?: string }) => {
                const { code, msg, data } = await postSyhtDictRuleGetDictRuleAll(params) as INoFenye<ISyhtDictRuleGetDictRuleAll>;
                if (code === 200) {
                    let arr: ISelectProps[] = []
                    data.forEach((item: ISyhtDictRuleGetDictRuleAll) => {
                        arr.push({
                            label: item.ruleName, // 规则名称
                            value: item.ruleId // 规则ID 
                        })
                    })
                    setParserRuleList([...arr]); // 解析规则列表
                } else {
                    alert(msg)
                }

            },
            [],
        )

        useEffect(() => {
            parserRuleFun({})
        }, [parserRuleFun])

        // 点击取消按钮
        const handleCancel = useCallback(
            () => {
                setAddrNum(''); // 地址序号
                setInfoName(''); // 信息点名称
                setParserRuleId(undefined); // 解析规则ID
                setWarnType(undefined); // 告警类型
                setEventColor(undefined); //事件颜色
                setIsStore('0'); //是否存储
                setStoreInterval(undefined); //     存储间隔
                setStoreDay(''); //     存储天数

            },
            [],
        )
        useEffect(() => {
            if (ModuleBoxRef.current && moduleBoxContentRef.current) {
                ModuleBoxRef.current.addEventListener('click', (event: any) => {
                    if (moduleBoxContentRef.current?.contains(event.target as Node)) {

                    } else {
                        handleCancel();
                        onClose();
                    }
                })
            }
        }, [handleCancel, onClose])
        // 回显
        const detailsFun = useCallback(
            async () => {
                if (clickId) {
                    const { code, msg, data } = await getSyhtDictEventItemGetDictEventItemById({ eventItemId: clickId }) as { code: number, msg: string, data: ISyhtDictEventItemGetDictEventItemById };
                    if (code === 200) {
                        setAddrNum(data.addrNum); // 地址序号
                        setInfoName(data.infoName); // 信息点名称
                        setParserRuleId(data.ruleId); // 解析规则ID 
                        setWarnType(data.warnType); // 告警类型
                        setEventColor(data.eventColor); //事件颜色
                        setIsStore(data.isStore); //是否存储
                        setStoreInterval(data.storeInterval); //     存储间隔
                        setStoreDay(data.storeDay); //     存储天数
                    }else{
                        alert(msg)
                    }
                }
            },
            [clickId],
        )

        useEffect(() => {
            detailsFun();
        }, [detailsFun])
        // 点击确定按钮
        const handleSumber = async () => {
            if (addrNum === '') {
                messageApi.warning('请输入地址序号')
            } else if (infoName === '') {
                messageApi.warning('请输入信息点名称')
            } else if (!parserRuleId) {
                messageApi.warning('请选择解析规则')
                return;
            } else if (!warnType) {
                messageApi.warning('请选择告警类型')
                return;
            } else if (!eventColor) {
                messageApi.warning('请选择事件颜色')
                return;
            } else if (!storeInterval) {
                messageApi.warning('请选择存储间隔')
                return;
            } else if (storeDay === '') {
                messageApi.warning('请输入存储天数')
                return;
            } else {
                if(eventId && clickId) {
                    const params: ISyhtDictEventItemUpdateEventItemParams = {
                        addrNum: addrNum, // 地址序号
                        eventColor: eventColor, // 事件颜色
                        eventId: eventId, // 事件ID 新增不需要传
                        infoName: infoName, // 信息点名称
                        isStore: isStore, // 是否存储 0 否 1 是
                        parserRule: parserRule, // 解析规则
                        ruleId: parserRuleId, // 解析规则ID 新增不需要传
                        storeDay: storeDay, // 存储天数
                        storeInterval: storeInterval, // 存储间隔 0 10s 1 1min 2 10min 3 1h 4 1day 5 1week 6 1month 7 1year
                        warnType: warnType, // 告警类型 
                        eventItemId: clickId // 信息点ID
                    }
                    const { code, msg } = await postSyhtDictEventItemUpdateEventItem(params) as { code: number, msg: string };
                    if (code === 200) {
                        messageApi.success('修改成功')
                        handleCancel()
                        onClose();
                    } else {
                        alert(msg)
                    }
                }else if(eventId){
                    const params: ISyhtDictEventItemAddEventItemParams = {
                        addrNum: addrNum, // 地址序号
                        eventColor: eventColor, // 事件颜色
                        eventId: eventId, // 事件ID 新增不需要传
                        infoName: infoName, // 信息点名称
                        isStore: isStore, // 是否存储 0 否 1 是
                        parserRule: parserRule, // 解析规则
                        ruleId: parserRuleId, // 解析规则ID 新增不需要传
                        storeDay: storeDay, // 存储天数
                        storeInterval: storeInterval, // 存储间隔 0 10s 1 1min 2 10min 3 1h 4 1day 5 1week 6 1month 7 1year
                        warnType: warnType, // 告警类型 
                    }
                    const { code, msg } = await postSyhtDictEventItemAddEventItem(params) as { code: number, msg: string };
                    if (code === 200) {
                        messageApi.success('添加成功')
                        handleCancel()
                        onClose();
                    } else {
                        alert(msg)
                    }
                }


            }





        }
        // 解析规则
        const handleChangeJiexi = (value: ISelectProps) => {
            setParserRuleId(value.value) // 解析规则
        }


        return <ModalBox ref={ModuleBoxRef} open={open}>
            <div ref={moduleBoxContentRef} className="modal-content" >
                <div className="modal-header">
                    <div className="modal-title">添加</div>
                    <span className="guanbi" aria-hidden="true" onClick={() => {
                        handleCancel()
                        onClose();
                    }}>&times;</span>
                </div>
                <div className="modal-body">
                    <FormBox>
                        <FormItemBox>
                            <div className="form_title_box">地址序号</div>
                            <InputX value={addrNum} onChange={(value) => setAddrNum(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">信息点名称</div>
                            <InputX value={infoName} onChange={(value) => setInfoName(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">解析规则</div>
                            <SelectX selectTreeList={parserRuleList} value={parserRuleId} onChange={(value) => handleChangeJiexi(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">告警类型</div>
                            <RadioX value={warnType} name="warnType" options={handleGetDictionaryItemValueLabel(dicWarnType)} onChange={(value) => setWarnType(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">事件颜色</div>
                            <SelectX selectTreeList={handleGetDictionaryItemValueLabel(dicColor)} value={eventColor} onChange={(value) => setEventColor(value.value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">是/否存储</div>
                            <RadioX value={isStore} name="isStore" options={isStoreList} onChange={(value) => setIsStore(value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">存储间隔</div>
                            <SelectX selectTreeList={handleGetDictionaryItemValueLabel(dicInterval)} value={storeInterval} onChange={(value) => setStoreInterval(value.value)} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">存储周期</div>
                            <InputX value={storeDay} onChange={(value) => setStoreDay(value)} />
                        </FormItemBox>

                    </FormBox>
                </div>
                <div className="modal-footer">
                    <div style={{ marginRight: '2rem' }}>
                        <ButtonX type="info" onClick={() => {
                            handleCancel()
                            onClose();
                        }}>取消</ButtonX>
                    </div>
                    <ButtonX type='primary' onClick={() => handleSumber()}>确定</ButtonX>
                </div>
            </div>
            {contextHolder}
        </ModalBox>
    }

export default AddChangeModule;